package root.electronclass.electronclass.other

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Environment
import android.os.Handler
import android.os.SystemClock
import android.provider.Settings
import android.view.View
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.core.os.postDelayed
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.FileIOUtils
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.SPUtils
import root.electronclass.electronclass.MainActivity
import root.electronclass.electronclass.MainActivity2
import root.electronclass.electronclass.common.base.CommonDialogFragment
import root.electronclass.electronclass.common.base.ViewBindingActivity
import root.electronclass.electronclass.databinding.ActivityDeviceCodeBinding
import root.electronclass.electronclass.mvp.GlobalParameter
import root.electronclass.electronclass.mvp.base.BaseResponse
import root.electronclass.electronclass.mvp.base.CallbackNext
import root.electronclass.electronclass.mvp.entity.EcardInfo
import root.electronclass.electronclass.mvp.entity.OrgSchoolInfoVO
import root.electronclass.electronclass.mvp.model.UserViewModel
import root.electronclass.electronclass.mvp.rest.RestManager
import root.electronclass.electronclass.other.dialog.SetDialog
import retrofit2.Call
import retrofit2.Response
import root.electronclass.electronclass.mvp.base.data
import root.electronclass.electronclass.mvp.entity.CheckPwdModel
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.security.MessageDigest
import java.util.*


/**
 * 获取设备唯一ID
 * 初始化main界面信息
 */
class DeviceCodeActivity : ViewBindingActivity<ActivityDeviceCodeBinding>() {
    private var mUserViewModel: UserViewModel? = null
    private val COUNTS = 4 // 点击次数
    private val DURATION: Long = 1000 // 规定有效时间
    private var mHits = LongArray(COUNTS)
    override fun init() {
        if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    arrayOf<String>(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)
        } else {
            getFile()
            binding.ip.text = NetworkUtils.getIPAddress(true)
            binding.version.text = AppUtils.getAppVersionName()
        }

        onClick()

    }

    private fun onClick() {
        binding.sure.setOnClickListener {
            pro = 0
            binding.progressBar.progress = pro
            deviceLogin()
        }

        binding.set.setOnClickListener {
            continuousClick(true)
        }
    }

    /**
     * logo连点判断
     */
    private fun continuousClick(b: Boolean) { //每次点击时，数组向前移动一位
        System.arraycopy(mHits, 1, mHits, 0, mHits.size - 1) //为数组最后一位赋值
        mHits[mHits.size - 1] = SystemClock.uptimeMillis()
        if (mHits[0] >= SystemClock.uptimeMillis() - DURATION) {
            mHits = LongArray(COUNTS) //重新初始化数组
            if (b) {
                SetDialog().apply {
                    arguments = bundleOf(CommonDialogFragment.TITLE to "班牌登陆", CommonDialogFragment.CLOSE to true,
                            CommonDialogFragment.CANCEL to "取消", CommonDialogFragment.OK to "确定")
                    onSubClick = {
                        checkPwd(it)
                    }
                }.show(supportFragmentManager, "SET")
            }
        }
    }

    private fun checkPwd(pwd: String?) {
        RestManager.getInstance().initRest().getSecret()
                .enqueue(object : CallbackNext<BaseResponse<CheckPwdModel>>(mDialogViewModel) {
                    override fun onSuccessful(call: Call<BaseResponse<CheckPwdModel>>?, response: BaseResponse<CheckPwdModel>) {
                        if (response.isSuccess) {
                            if (pwd == response.data.secret) {
                                startActivity(Intent(Settings.ACTION_SETTINGS))
                            }else{
                                toast("密码错误")
                            }
                        }else{
                            toast("密码错误")
                        }
                    }

                    override fun onError(call: Call<BaseResponse<CheckPwdModel>>?, response: BaseResponse<CheckPwdModel>?) {
                        toast(response?.msg)
                    }

                    override fun onFail(call: Call<BaseResponse<CheckPwdModel>>?, t: Throwable?, response: Response<BaseResponse<CheckPwdModel>>?) {

                    }

                })
    }

    private fun getFile() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            var device = SPUtils.getInstance().getString("Device_code", null)
            if (device == null) {
                device = generate8CharString(Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID))
                SPUtils.getInstance().put("Device_code", device)
            }
            binding.sure.visibility = View.GONE
            binding.cardNum.text = device
        } else {
            val path = Environment.getExternalStorageDirectory().path + "/" + "device_code.txt"
            if (FileUtils.isFileExists(path)) {
                val read = FileIOUtils.readFile2String(path)
                binding.cardNum.text = read
                LogUtils.i("getFile-file:$read")
                binding.sure.visibility = View.GONE
            } else {
                binding.sure.visibility = View.VISIBLE
                val str = StringBuilder() //定义变长字符串
                val random = Random() //随机生成数字，并添加到字符串
                for (i in 0..7) {
                    str.append(random.nextInt(10))
                }
                binding.cardNum.text = str.toString()
                FileIOUtils.writeFileFromString(path, str.toString())
                LogUtils.i("getFile-random:$str")
            }

        }

        GlobalParameter.setDeviceCode(binding.cardNum.text.toString())
        if (!SPUtils.getInstance().getBoolean("runResult", true)) {
            binding.sure.visibility = View.VISIBLE
            return
        }
        deviceLogin()
    }

    // 生成8位字符串
    private fun generate8CharString(input: String): String { // 使用SHA-256生成哈希值
        val md = MessageDigest.getInstance("SHA-256")
        val hash = md.digest(input.toByteArray(Charsets.UTF_8))
        val hexString = hash.joinToString("") { "%02x".format(it) }

        // 截取前8位字符
        return hexString.take(8).uppercase(Locale.getDefault())
    }

    private var pro: Int = 0

    private fun deviceLogin() {
        var deviceID = binding.cardNum.text.toString().trim()

//        deviceID = "03130156"
        LogUtils.iTag("设备号deviceID", deviceID)
        RestManager.getInstance().initRest().deviceLogin(deviceID) //        RestManager.getInstance().initRest().deviceLogin("02753637")
                .enqueue(object : CallbackNext<BaseResponse<String>>(mDialogViewModel) {
                    override fun onSuccessful(
                        call: Call<BaseResponse<String>>?,
                        response: BaseResponse<String>,
                    ) {
                        if (response.isSuccess) {
                            RestManager.getInstance().token = response.rows
                            RestManager.getInstance().initService()
                            getSchoolInfo()
                            getElectorInfo(deviceID) //                        getElectorInfo("333")
                        }
                        pro += 32
                        setProgress()
                    }

                    override fun onError(
                        call: Call<BaseResponse<String>>?,
                        response: BaseResponse<String>?,
                    ) {
                        toast(response?.msg)
                        binding.sure.visibility = View.VISIBLE

                    }

                    override fun onFail(
                        call: Call<BaseResponse<String>>?,
                        t: Throwable?,
                        response: Response<BaseResponse<String>>?,
                    ) {
                        binding.sure.visibility = View.VISIBLE

                    }

                })
    }

    private fun getSchoolInfo() {
        RestManager.getInstance().initRest().schoolInfo().enqueue(object : CallbackNext<BaseResponse<OrgSchoolInfoVO>>(mDialogViewModel) {

            override fun onSuccessful(
                call: Call<BaseResponse<OrgSchoolInfoVO>>,
                response: BaseResponse<OrgSchoolInfoVO>,
            ) {
                if (response.isSuccess) {
                    GlobalParameter.setSchoolInfo(response.rows)

                    pro += 34
                    setProgress()
                }
            }

            override fun onError(
                call: Call<BaseResponse<OrgSchoolInfoVO>>,
                response: BaseResponse<OrgSchoolInfoVO>,
            ) {
                binding.sure.visibility = View.VISIBLE

            }

            override fun onFail(
                call: Call<BaseResponse<OrgSchoolInfoVO>>?,
                t: Throwable?,
                response: Response<BaseResponse<OrgSchoolInfoVO>>?,
            ) {
                binding.sure.visibility = View.VISIBLE

            }

        })
    }


    private fun getElectorInfo(cardNo: String) {
        RestManager.getInstance().initRest().getElectorInfo(cardNo).enqueue(object : CallbackNext<BaseResponse<EcardInfo>>(mDialogViewModel) {

            override fun onSuccessful(
                call: Call<BaseResponse<EcardInfo>>,
                response: BaseResponse<EcardInfo>,
            ) {
                if (response.isSuccess) {
                    GlobalParameter.setEcardInfo(response.rows)
                    pro += 34
                    setProgress()
                }
            }

            override fun onError(
                call: Call<BaseResponse<EcardInfo>>,
                response: BaseResponse<EcardInfo>,
            ) {
                binding.sure.visibility = View.VISIBLE

            }

            override fun onFail(
                call: Call<BaseResponse<EcardInfo>>?,
                t: Throwable?,
                response: Response<BaseResponse<EcardInfo>>?,
            ) {
                binding.sure.visibility = View.VISIBLE

            }

        })
    }

    private fun setProgress() {
        binding.progressBar.progress = pro
        if (pro == 100) {

            if (GlobalParameter.getEcardInfo().classId == null) {
                startActivity(Intent(this@DeviceCodeActivity, MainActivity2::class.java))
            } else {
                startActivity(Intent(this@DeviceCodeActivity, MainActivity::class.java))
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<String?>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 1) {
            if (grantResults.isNotEmpty() && grantResults.all { it == PackageManager.PERMISSION_GRANTED }) { // 所有权限都已授予
                getFile()
                binding.ip.text = NetworkUtils.getIPAddress(true)
                binding.version.text = AppUtils.getAppVersionName()
            } else { // 至少有一个权限被拒绝
            }
        }
    }
}